import {
	Toast
} from 'vant';
import store from '@/store/index'

let socketTimeout = null;
export const initSocket = (params = {}) => {
	window.windowsSdkSocket = {
		socket: new WebSocket('ws://127.0.0.1:4321'), //socket实例
		params: {}, //存的请求参数
		state: 'fail', //socket状态
	}
	windowsSdkSocket.socket.onopen = () => {
		windowsSdkSocket.state = 'success';
		store.commit('setWindowsSdkSocketState', 'success')
		console.log("Windows硬件服务[Socket连接成功]");
		params.success && params.success();
	};
	windowsSdkSocket.socket.onerror = e => {
		windowsSdkSocket.state = 'fail';
		store.commit('setWindowsSdkSocketState', 'fail')
		console.log(e, "socket连接失败");
		params.fail && params.fail();
	};
	windowsSdkSocket.socket.onclose = e => {
		//重连
		if (socketTimeout) clearTimeout(socketTimeout);
		socketTimeout = setTimeout(() => {
			console.log('socket重连')
			initSocket();
		}, 5000)
	};
	let noToastNameList = ['AIOT_iVerifyPINWithPass', 'AIOT_iReadCardBas', 'READSOCIALSECURITYCARD',
		'READCARDREADMAGCARDNO', 'DETECTSTATE', 'ShenFenZhengSingle', 'READCARDTESTINSERTCARD',
	]
	windowsSdkSocket.socket.onmessage = res => {
		// res.data=res.data.replace(/\\/g, '/');//处理返回的内容有反斜杠；
		if (!res.data) {
			return
		}
		res = JSON.parse(res.data)
		res.data = {};
		res.arguments.forEach((t) => {
			res.data[t.id] = t.text
		});
		delete res.arguments;
		if (res.name != "DETECTSTATE") {
			console.log('\x1B[41m%s\x1B[0m', '------', `socket收到[${res.name}]:`, JSON.stringify(res))
		}
		if (res.name == 'BILLACCEPTORSTACKMONEYDETAIL') {
			//获取纸币器，存钞明细的时候返回会没有ERROR这个字段
			res.data.ERROR = 'SUCCESS'
		}
		if (res.data.ERROR != 'SUCCESS') {
			let msg = res.data.MSG || res.data.ERROR || `[${res.name}]硬件服务异常`;
			if (noToastNameList.indexOf(res.name) < 0 && res.data.ERROR.indexOf('纸将尽') < 0) {
				Toast({
					message: msg,
				});
			}
		}
		if (res.name == 'FACEQRCODE') {
			//刷脸获取付款码，处理底层name返回不对应的问题，
			res.name = 'FACEPAYCODE'
		}

		windowsSdkSocket.params[res.name] && windowsSdkSocket.params[res.name].success && windowsSdkSocket
			.params[res.name].success(res.data)
	};
};
export const closeSocket = () => {
	if (windowsSdkSocket.socket) {
		windowsSdkSocket.socket.close();
	}
};
export const sendSocket = (params) => {
	let data = {
		arguments: [],
		name: params.name,
	};
	for (let attr in params.data) {
		data.arguments.push({
			id: attr,
			text: params.data[attr]
		})
	};
	windowsSdkSocket.params[params.name] = params;
	if (params.name != "DETECTSTATE") {
		console.log('\x1B[40m%s\x1B[0m', '------', `socket发送[${params.name}]:`, JSON.stringify(params))
	}

	windowsSdkSocket.socket.send(JSON.stringify(data));
};

export default {
	//刷脸
	getUserInfoByFace(params) {
		sendSocket({
			name: 'FACEAUTH',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//刷脸获取付款码
	getPayCodeByFace(params) {
		sendSocket({
			name: 'FACEPAYCODE',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//刷身份证（监听模式）
	onMonitorIdCardReader(callback) {
		sendSocket({
			name: 'SHENFENZHENG',
			success: (res) => {
				callback(res);
			}
		})
	},
	//身份证单次读取：open:打卡端口，close:关闭端口，read:读取
	idCardReaderSingle(params) {
		return new Promise((resolve, reject) => {
			sendSocket({
				name: 'ShenFenZhengSingle',
				data: params.data,
				success: (res) => {
					params.success && params.success(res);
					resolve(res);
				},
			})
		})
	},
	//刷身份证
	idCardReader(params) {
		sendSocket({
			name: 'SHENFENZHENG',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//查询身份证阅读器状态
	queryIdcardStatus(params) {
		sendSocket({
			name: 'SHENFENZHENGSTATUS',
			success: (res) => {
				params.success(res);
			}
		})
	},

	//查询凭条打印机状态
	querySlipPrint(params) {
		sendSocket({
			name: 'RECEIPTSTATUS',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//查询报告打印机状态
	queryReportPrint(params) {
		sendSocket({
			name: 'LASERPRINTSTATUS',
			success: (res) => {
				params.success(res);
			}
		})
	},

	//凭条打印（图片）
	slipPrintForImg(params) {
		console.log(params)
		let style = document.querySelector('style');
		let data = JSON.stringify({
			data: [{
					"type": 6,
					"content": style.outerHTML,
				},
				{
					"type": 6,
					"content": `<img src='${params.data.rawData}'>`,
				},
				{
					"type": 6,
					"content": params.data.outerHTML,
				},
			]
		})

		sendSocket({
			name: 'slipPrint',
			data: {
				content: data,
			},
			success: (res) => {
				params.success(res);
			}
		})
	},
	//凭条打印
	slipPrint(params) {
		let data = JSON.stringify({
			data: [
				{
					"type": 6,
					"content": '<style>*{line-height:26px;}</style>',
				},
				...params.data,
			],
		})
		sendSocket({
			name: 'slipPrint',
			data: {
				content: data,
			},
			success: (res) => {
				params.success(res);
			}
		})
	},
	//报告打印
	reportPrint(params) {
		sendSocket({
			name: 'XHPrintReport',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//读社保卡（单次读取）
	readSsCard(params) {
		sendSocket({
			name: 'READSOCIALSECURITYCARD',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//读社保卡2（单次读取）
	readSsCard2(params) {
		sendSocket({
			name: 'AIOT_iReadCardBas',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//移动到IC卡位
	moveCardToIc(params) {
		sendSocket({
			name: 'READCARDMOVECARDTOIC',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//设置内外部读卡
	setInOutModel(params) {
		sendSocket({
			name: 'READCARDSETINOUTMODEL',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//允许进磁条卡
	openMagneticStripeCard(params) {
		sendSocket({
			name: 'READCARDALLOWCARDIN',
			data: {
				ONLY_MAG: "TRUE",
			},
			success: (res) => {
				params && params.success(res);
			}
		})
	},
	//禁止进磁条卡
	closeMagneticStripeCard(params) {
		sendSocket({
			name: 'READCARDNOTALLOWCARDIN',
			success: (res) => {
				console.log(res)
			}
		})
	},
	//获取读卡器状态
	getMagneticStripeCardStatus(params) {
		sendSocket({
			name: 'READCARDTESTINSERTCARD',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//读磁条卡（单次读取）
	readMagneticStripeCard(params) {
		sendSocket({
			name: 'READCARDREADMAGCARDNO',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//退磁条卡
	outMagneticStripeCard(params) {
		sendSocket({
			name: 'READCARDOUTCARD',
			data: {
				ONLY_MAG: 'TRUE'
			},
			success: (res) => {
				params.success(res);
			}
		})
	},
	//写磁条卡
	writeMagneticStripeCard(params) {
		sendSocket({
			name: 'WRITECARD',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//发磁条卡
	sendMagneticStripeCard(params) {
		sendSocket({
			name: 'GETCARD',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//发卡器（获取状态）
	cardSenderStatus(params) {
		sendSocket({
			name: 'CARDSENDERGETSTATUS',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//发卡器（读卡）
	cardSenderRead(params) {
		sendSocket({
			name: 'CARDSENDERREADCARD',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//发卡器（回收）
	cardSenderRecovery(params = {}) {
		sendSocket({
			name: 'CARDSENDERRECYCLE',
			success: (res) => {
				params.success && params.success(res);
			}
		})
	},
	//发卡器（吐卡）
	cardSenderTuka(params) {
		sendSocket({
			name: 'CARDSENDEROUTCARD',
			success: (res) => {
				// params.success(res);
			}
		})
	},
	//现金充值
	cashRecharge(params) {
		sendSocket({
			name: 'CHONGZHI',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//语音播报
	speak(params) {
		sendSocket({
			name: 'DoSpeech',
			data: params.data,
			success: (res) => {}
		})
	},
	//打开键盘
	openKeyboard(params) {
		sendSocket({
			name: 'OPENKEYBOARD',
			data: {
				OPEN: '1'
			},
			success: (res) => {}
		})
	},
	//关闭键盘
	closeKeyboard(params) {
		sendSocket({
			name: 'OPENKEYBOARD',
			data: {
				OPEN: '0'
			},
			success: (res) => {}
		})
	},
	//获取设备sn号
	getSerialNumber(params) {
		sendSocket({
			name: 'machineId',
			success: (res) => {
				params.success(res);
			}
		})
	},
	//开门禁锁
	openLock(params) {
		sendSocket({
			name: 'LOCKOPEN',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//关门禁锁
	closeLock(params) {
		sendSocket({
			name: 'LOCKCLOSE',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//一次性拍照
	takePhoto(params) {
		sendSocket({
			name: 'TAKEPHOTO',
			data: params.data,
			success: (res) => {
				// params.success(res);
			}
		})
	},
	//连续拍照开始拍照
	openTakePhotoContinuous(params) {
		sendSocket({
			name: 'TAKEPHOTOSTART',
			data: params.data,
			success: (res) => {
				// params.success(res);
			}
		})
	},
	//连续拍照结束拍照
	closeTakePhotoContinuous(params) {
		sendSocket({
			name: 'TAKEPHOTOEND',
			data: params.data,
			success: (res) => {
				// params.success(res);
			}
		})
	},
	//打开灯光
	openLight(params) {
		//1是摄像头补光灯，2报告打印机灯 3社保卡读卡器 6身份证读卡器 4操作台红灯 5操作台绿灯 19发卡器
		sendSocket({
			name: 'DOORLIGHTOPEN',
			data: params.data,
			success: (res) => {}
		})
	},
	//关闭灯光
	closeLight(params) {
		sendSocket({
			name: 'DOORLIGHTCLOSE',
			data: params.data,
			success: (res) => {}
		})
	},
	//闪烁灯光
	flushLight(params) {
		sendSocket({
			name: 'DOORLIGHTFLUSH',
			data: params.data,
			success: (res) => {}
		})
	},
	//三色灯
	ledLight(params) {
		if (params.data.rgb == '蓝') {
			params.data.rgb = '001'
		} else if (params.data.rgb == '红') {
			params.data.rgb = '100'
		}
		sendSocket({
			name: 'LEDLight',
			data: params.data,
			success: (res) => {}
		})
	},
	//红外感应状态检测
	infraredSensing(params) {
		sendSocket({
			name: 'DETECTSTATE',
			data: params.data,
			success: (res) => {
				params.success(res);
			}
		})
	},
	//设置自动开关机
	autoBoot(params) {
		sendSocket({
			name: 'AUTOBOOT',
			data: params.data,
			success: (res) => {}
		})
	},
	//取消自动开关机
	stopShutdown(params) {
		sendSocket({
			name: 'STOPSHUTDOWN',
			success: (res) => {}
		})
	},
	//打开纸币器
	openBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTOROPENPORT',
			data: params.data,
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//关闭纸币器
	closeBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTORCLOSEPORT',
			data: params.data,
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//获取存钞明细
	getBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTORSTACKMONEYDETAIL',
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//设置纸币入币金额
	setBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTORSETCASHINMONEY',
			data: {
				AVAILABLE: '10,20,50,100',
				...params.data,
			},
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//获取纸币器状态
	getBanknoteDispenserStatus(params) {
		sendSocket({
			name: 'BILLACCEPTORGETSTATUS',
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//允许纸币入币
	canBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTORALLOWCASHIN',
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},
	//禁止纸币入币
	notCanBanknoteDispenser(params) {
		sendSocket({
			name: 'BILLACCEPTORNOTALLOWCASHIN',
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				}
			}
		})
	},

	//社保卡PIN码校验（前端出ui密码框）
	iVerifyPINWithPass(params) {
		sendSocket({
			name: 'AIOT_iVerifyPINWithPass',
			data: params.data,
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					params.success(res);
				} else {
					params.fail(res);
				}
			}
		})
	},
	//刷脸初始化
	faceInit(params) {
		return new Promise((resolve, reject) => {
			sendSocket({
				name: 'FACEINIT',
				success: (res) => {
					resolve(res);
				},
			})
		})
	},
	/* 有流程的封装-------------------------------------------------------------- */
	//退卡
	outCard(params) {
		this.getMagneticStripeCardStatus({
			success: (res) => {
				if (res.ERROR == 'SUCCESS') {
					if (res.CARDSTACKSTATE == '1' || res.CARDSTACKSTATE == '2') {
						this.outMagneticStripeCard({
							success: (res2) => {
								if (res2.ERROR == 'SUCCESS') {
									this.closeMagneticStripeCard()
								}
							}
						})
					}
				}
			}
		})
	},


}